import { resizeImageData } from '../../imageResizer'

const app = getApp()
const log = t => getApp().globalData.logger.log('[takePicResult]' + t)
let systemInfo
let frame

function getBase64StringFromArrayBuffer(rawImageData) {
  const jpegEncoder = require('../../jpegEncoder.js')
  const base64Encoder = require('../../base64.js')
  log('JPEG encoding started')
  const jpg = jpegEncoder(
    {
      width: rawImageData.width,
      height: rawImageData.height,
      data: new Uint8ClampedArray(rawImageData.data)
    },
    90
  )
  log('JPEG encoding finished')
  log('Base64 encoding started')
  const base64 = base64Encoder.binaryToBase64(jpg.data)
  log('Base64 encoding finished')
  return Promise.resolve('data:image/jpg;base64,' + base64)
}

Page({
  data: {
    canvasW: 0,
    canvasH: 0,
    resultImage: '',
    usageImageView: true,
    pixelRatio: 1
  },

  onLoad() {
    frame = app.globalData.takePicture.frame
    if (!frame) {
      log('No picture data')
      my.navigateBack()
      return
    }

    systemInfo = app.globalData.systemInfo
    const ratio = frame.height / frame.width
    const canvasW = systemInfo.windowWidth
    const canvasH = systemInfo.windowWidth * ratio
    this.setData({
      canvasW: canvasW,
      canvasH: canvasH,
      pixelRatio: parseInt(systemInfo.pixelRatio)
    })
  },

  onReady: function() {
    const resized = resizeImageData(frame, this.data.canvasW * this.data.pixelRatio, this.data.canvasH * this.data.pixelRatio)
    if (this.data.usageImageView) {
      getBase64StringFromArrayBuffer(resized).then(base64 => {
        this.setData({
          resultImage: base64
        })
      })
    } else {
      const ctx = my.createCanvasContext('previewCanvas')
      ctx.putImageData({
        ...resized,
        x: 0,
        y: 0,
        fail: err => {
          log('putImageData err=' + JSON.stringify(err))
        }
      })
    }
  }
})
